<template>
  <div class="card-content">
    <div class="chat-wrap">
      <div class="chat-box">
        <!-- 聊天消息显示区域 -->
        <div class="chat-messages">
          <div
            v-for="(message, index) in chatMessages"
            :key="index"
            class="one-msg"
          >
            <div v-if="message.isSelf" class="message self-message">
              {{ message.text }}
            </div>
            <div v-else>
              <div class="tip1">
                <!-- 修改：添加条件判断 -->
                <span
                  v-if="
                    message.think && thinkDisplayLength < message.think.length
                  "
                >
                  <i class="iconfont iconshendusikao icon" /> 思考中...
                  <i class="iconfont iconxiangshang"></i>
                </span>
                <span v-else>
                  <i class="iconfont iconshendusikao icon" />
                  已深度思考（用时9秒） <i class="iconfont iconxiangshang"></i>
                </span>
              </div>
              <!-- 修改：使用 substring 截取显示的字符 -->
              <div
                class="think"
                v-html="message.think.substring(0, thinkDisplayLength)"
              ></div>
              <div
                class="other-message"
                v-html="message.text.substring(0, textDisplayLength)"
              ></div>
              <div
                id="chart"
                style="width: 100%; height: 400px"
                v-if="showChart"
              ></div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="message-container">
      <!-- 消息输入框，添加 keyup 事件监听 -->
      <textarea
        v-model="inputMessage"
        class="tip"
        placeholder="给菜包发送消息"
        style="resize: none"
        @keyup.enter="sendMessage"
      />
      <div class="button-group">
        <div :class="buttonClass1" @click="onClick1">
          <i class="iconfont iconshendusikao icon" /> 深度思考 (R1)
        </div>
        <div :class="buttonClass2" @click="onClick2">
          <i class="iconfont iconwangzhan icon" /> 联网搜索
        </div>

        <div style="flex: 1"></div>
        <!-- 发送消息按钮 -->

        <img :class="iconClass" src="../assets/img3.png " />
        <!-- <img :class="iconClass2" src="../assets/img5.png " /> -->
        <div class="send-button" @click="sendMessage">发送</div>
      </div>
    </div>
  </div>
</template>

<script>
import MyButton from "./MyButton.vue";
import * as echarts from "echarts";
// 引入 data1.json 文件
import data1 from "../data/data1.json";
import think from "../data/think.json";
import { nextTick } from "vue";
// 引入事件总线
import { bus } from "../eventBus";

export default {
  components: {
    MyButton,
  },
  data() {
    return {
      buttonClass1: {
        "deep-thought": true,
        "deep-thought-active": true,
      },
      buttonClass2: {
        "deep-thought": true,
        "deep-thought-active": false,
      },
      iconClass: {
        icon2: true,
        "icon2-active": false,
      },
      iconClass2: {
        icon2: true,
        "icon2-active": true,
      },
      btnType: "",
      btnSize: "",
      // 存储聊天消息的数组
      chatMessages: [],
      // 输入框中的消息
      inputMessage: "",
      // 新增：用于控制打字机效果的显示字符数量
      thinkDisplayLength: 0,
      // 新增：用于控制 message.text 打字机效果的显示字符数量
      textDisplayLength: 0,
      // 控制图表是否显示
      showChart: false,
      // 新增：定义 option1 变量并赋值
      option1: data1,
    };
  },
  mounted() {
    // 在组件挂载后开始打字机效果
    this.typeWriter();
  },
  methods: {
    onClick1() {
      this.buttonClass1["deep-thought-active"] =
        !this.buttonClass1["deep-thought-active"];
    },
    onClick2() {
      this.buttonClass2["deep-thought-active"] =
        !this.buttonClass2["deep-thought-active"];
    },
    // 发送消息的方法
    sendMessage() {
      if (this.inputMessage.trim() !== "") {
        bus.emit("message-sent", this.inputMessage);

        this.chatMessages.push({ text: this.inputMessage, isSelf: true });
        // 模拟收到回复，实际应用中这里应替换为真实的接口调用
        setTimeout(() => {
          this.chatMessages.push({
            text: think.text,
            isSelf: false,
            think: think.data,
          });
          // 每次收到新回复时重置打字机效果
          this.thinkDisplayLength = 0;
          this.textDisplayLength = 0;
          this.showChart = false;
          this.typeWriter();
        }, 1000);
        this.inputMessage = "";
      }
    },
    // 新增：打字机效果方法
    typeWriter() {
      const message = this.chatMessages.find((msg) => !msg.isSelf);
      if (message) {
        if (this.thinkDisplayLength < message.think.length) {
          this.thinkDisplayLength++;
          setTimeout(() => {
            this.typeWriter();
            this.scrollToBottom(); // 调用滚动方法
          }, 10);
        } else if (this.textDisplayLength < message.text.length) {
          this.textDisplayLength++;
          setTimeout(() => {
            this.typeWriter();
            this.scrollToBottom(); // 调用滚动方法
          }, 1);
        } else {
          // 当 message.text 打字完成后，显示图表
          this.showChart = true;
          nextTick(() => {
            const chartDom = document.getElementById("chart");
            const myChart = echarts.init(chartDom);

            let updatetime = [];
            let dataVelocity = [];
            let dataTemperature = [];

            let n = 1; // 前n分钟
            let m = 2; // n - m分钟
            let randomTemp = 1; // 温度波动范围，默认值为2
            let randomFluctuation = 0.05; // 可配置的振动随机波动范围，默认值为0.05

            const endTime = new Date();
            const startTime = new Date(endTime.getTime() - 5 * 60 * 1000);
            const nMinutes = n * 60 * 1000;
            const mMinutes = m * 60 * 1000;
            for (
              let time = new Date(endTime.getTime() - 5 * 60 * 1000);
              time <= endTime;
              time.setSeconds(time.getSeconds() + 3)
            ) {
              let elapsedSeconds =
                (time.getTime() - startTime.getTime()) / 1000;
              let wz_velocity;
              let temperature;
              if (elapsedSeconds < n * 60) {
                wz_velocity =
                  1.2 + (Math.random() - 0.5) * 2 * randomFluctuation;
                temperature = 50 + (Math.random() - 0.5) * 2 * randomTemp;
              } else if (elapsedSeconds < m * 60) {
                // 确保 wz_velocity 能在第n到m分钟逐步降到0.4
                wz_velocity =
                  1.2 -
                  (0.8 * (elapsedSeconds - n * 60)) / ((m - n) * 60) +
                  (Math.random() - 0.5) * 2 * randomFluctuation;
                temperature =
                  50 +
                  (10 * (elapsedSeconds - n * 60)) / ((m - n) * 60) +
                  (Math.random() - 0.5) * 2 * randomTemp;
              } else {
                wz_velocity =
                  0.4 + (Math.random() - 0.5) * 2 * randomFluctuation;
                temperature = 60 + (Math.random() - 0.5) * 2 * randomTemp;
              }

              function formatTime(date) {
                const hours = String(date.getHours()).padStart(2, "0");
                const minutes = String(date.getMinutes()).padStart(2, "0");
                const seconds = String(date.getSeconds()).padStart(2, "0");
                return `${hours}:${minutes}:${seconds}`;
              }
              updatetime.push(formatTime(time));
              dataVelocity.push(wz_velocity);
              dataTemperature.push(temperature);
            }

            console.log(updatetime, dataVelocity);

            myChart.setOption({
              title: { text: "过去5分钟数据", left: 20, top: 10 },
              legend: {
                data: ["速度", "温度"],
                backgroundColor: "#f5f5f5",
                borderColor: "#ccc",
                borderWidth: 1,
              },
              xAxis: {
                data: updatetime,
                splitLine: { show: true, lineStyle: { type: "dashed" } },
                axisLabel: {
                  rotate: 0, // 增加标签旋转角度，防止数据挤在一起
                  fontSize: 10, // 调整字体大小
                  margin: 10, // 增加标签与轴的距离
                },
              },
              yAxis: [
                {
                  type: "value",
                  name: "速度",
                  splitLine: { show: true, lineStyle: { type: "dashed" } },
                  axisLabel: {
                    fontSize: 12, // 调整字体大小
                    margin: 10, // 增加标签与轴的距离
                  },
                },
                {
                  type: "value",
                  name: "温度",
                  splitLine: { show: true, lineStyle: { type: "dashed" } },
                  axisLabel: {
                    fontSize: 12, // 调整字体大小
                    margin: 10, // 增加标签与轴的距离
                  },
                  min: 40,
                  position: "right",
                },
              ],
              grid: {
                left: "3%", // 调整图表左边距
                right: "3%", // 调整图表右边距
                bottom: "60", // 增加底部边距，为旋转的标签留出空间
                top: "80",
                containLabel: true, // 确保标签不会被裁剪
              },
              dataZoom: [
                {
                  type: "slider",
                  xAxisIndex: 0,
                  filterMode: "empty",
                },
              ],
              series: [
                {
                  name: "速度",
                  type: "line",
                  smooth: true, // 启用平滑效果
                  data: dataVelocity,
                  lineStyle: { width: 2 }, // 增加线条宽度
                  itemStyle: { borderWidth: 1 }, // 增加数据点边框
                  // label: {
                  //   show: true,
                  //   position: "top",
                  //   textStyle: { fontSize: 16, color: "#333" },
                  // },
                  showSymbol: false,
                },
                {
                  name: "温度",
                  type: "line",
                  smooth: true, // 启用平滑效果
                  data: dataTemperature,
                  lineStyle: { width: 2 }, // 增加线条宽度
                  itemStyle: { borderWidth: 1 }, // 增加数据点边框
                  // label: {
                  //   show: true,
                  //   position: "top",
                  //   textStyle: { fontSize: 16, color: "#333" },
                  // },
                  yAxisIndex: 1,
                  showSymbol: false,
                },
              ],
            });

            this.scrollToBottom(); // 调用滚动方法
          });
        }
      }
    },
    scrollToBottom() {
      const chatBox = this.$el.querySelector(".chat-box");
      if (chatBox) {
        chatBox.scrollTop = chatBox.scrollHeight;
      }
    },
  },
};
</script>

<style>
li {
  line-height: 30px;
}
</style>
<style scoped>
.card-content {
  width: 100%;
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
}
.message-container {
  background-color: #f3f4f6;
  border-radius: 15px;
  padding: 10px;
  width: 65%;
  height: 100px;
  color: #aeaeb0;
  margin: 10px 0;
  flex-shrink: 0;
  /* box-sizing: border-box; */
}
.tip {
  height: 60px;
  width: 100%;
  border: none;
  background-color: #f3f4f6;
  font-size: 16px;
  color: #666;
}
.tip:focus {
  outline: none;
}
.button-group {
  display: flex;
  gap: 10px;
  /* margin-top: 20px; */
  align-items: center;
}

.deep-thought {
  background-color: #fff;
  padding: 5px;
  border-radius: 10px;
  color: #666;
  display: flex;
  align-items: center;
  gap: 5px;
  font-size: 14px;
  cursor: pointer;
}
.deep-thought-active {
  color: #4d6bfe;
}
.icon {
  width: 15px;
}
.icon2 {
  width: 20px;
}
.icon3 {
  width: 25px;
}
.icon2-active {
  opacity: 0.3;
}

.btn-group {
  display: flex;
  gap: 10px;
}

.chat-wrap {
  width: 100%;
  flex: 1;
}
.chat-box {
  height: 100%;
  max-height: calc(100vh - 240px); /* 减去一些边距或内边距 */
  overflow-y: auto; /* 如果内容超出，则显示滚动条 */
  display: flex;
  justify-content: center;
}
.chat-messages {
  width: 65%;
  box-sizing: border-box;
  padding: 10px;
  display: flex;
  flex-direction: column;
}
.message {
  background-color: #e2e8f0;
  border-radius: 8px;
  padding: 12px;
  margin-bottom: 10px;
  max-width: 70%;
  width: auto;
}
.self-message {
  background-color: #4d6bfe;
  color: white;
  margin-left: auto;
}
.other-message {
  margin-right: auto;
}
.send-button {
  background-color: #4d6bfe;
  color: white;
  padding: 5px 10px;
  border-radius: 8px;
  cursor: pointer;
}
.one-msg {
  display: flex;
}
.tip1 {
  color: #656565;
  font-size: 14px;
  height: 30px;
  line-height: 30px;
}
.think {
  color: #656565;
  font-size: 14px;
  border-left: 2px solid #eee;
  padding-left: 10px;
}
</style>